//
//  WeAuctionMapSelectView.m
//  WeGalaxy
//
//  Created by Zheng on 2017/7/11.
//  Copyright © 2017年 Zheng. All rights reserved.
//

#import "WeAuctionMapSelectView.h"

@interface WeAuctionMapSelectView ()

@property (nonatomic, strong) UIButton *indexBtn;
@property (nonatomic, strong) UIView *redView;

@end

@implementation WeAuctionMapSelectView
#pragma mark - 初始化
- (instancetype)init {
    self = [super init];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        self.showsVerticalScrollIndicator = NO;
        self.showsHorizontalScrollIndicator = NO;
        [self addSubview:self.redView];
    }
    return self;
}

#pragma mark - 设置titles
- (void)setTitles:(NSArray<NSString *> *)titles {
    _titles = titles;
    
    CGFloat height = 38;
    CGFloat singleWidth = kSCREEN_WIDTH/4.f;
    CGFloat totalWidth = singleWidth*_titles.count;
    self.contentSize = (CGSize){totalWidth,height};
    
    [_titles enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIButton *sBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        sBtn.frame = (CGRect){idx*singleWidth,0,singleWidth,height};
        sBtn.titleLabel.font = kCX_FONT(14);
        [sBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [sBtn setTitleColor:kRGB_COLOR(245, 67, 55, 1) forState:UIControlStateSelected];
        [sBtn setTitle:obj forState:UIControlStateNormal];
        [sBtn setTitle:obj forState:UIControlStateSelected];
        sBtn.tag = 12930+idx;
        [sBtn addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:sBtn];
        
        if (idx == 0) {
            sBtn.selected = YES;
            _indexBtn = sBtn;
        }
        
    }];
}

#pragma mark - 点击事件
- (void)clickAction:(UIButton *)sender {
    
    if (sender != _indexBtn) {

        CGFloat sWidth = sender.frame.size.width;
        CGFloat sOriginX = sender.frame.origin.x;
        CGFloat sHeight = sender.frame.size.height;
        CGFloat sOriginY = sender.frame.origin.y;
        CGFloat sAdjustX = (sender.tag > _indexBtn.tag)? sOriginX+sWidth: sOriginX-sWidth;
        CGRect visibleRect = (CGRect){sAdjustX,sOriginY,sWidth,sHeight};
        [self scrollRectToVisible:visibleRect animated:YES];
        
        _indexBtn.selected = !_indexBtn.selected;
        sender.selected = !sender.selected;
        _indexBtn = sender;
        
        [UIView animateWithDuration:kANIMATION_DURATION animations:^{
            _redView.frame = (CGRect){sOriginX,35,sWidth,3};
        }];
        
    }

    kCX_LOG(@"点击了%@", sender.titleLabel.text);
    
}


#pragma mark - 子视图
- (UIView *)redView {
    if (!_redView) {
        _redView = [UIView new];
        _redView.frame = (CGRect){0,35,kSCREEN_WIDTH/4.f,3};
        _redView.backgroundColor = kRGB_COLOR(245, 67, 55, 1);
    }
    return _redView;
}

@end
